<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>考试记录 - 学生端</title>
    <link rel="stylesheet" href="../css/common.css">
    <style>
        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }

        .page-header {
            background: linear-gradient(135deg, #17a2b8 0%, #138496 100%);
            color: white;
            padding: 30px;
            border-radius: 15px;
            margin-bottom: 30px;
            text-align: center;
        }

        .page-title {
            font-size: 2.5em;
            margin: 0;
            font-weight: 300;
        }

        .page-subtitle {
            font-size: 1.1em;
            margin: 10px 0 0 0;
            opacity: 0.9;
        }

        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }

        .stat-card {
            background: white;
            padding: 25px;
            border-radius: 15px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
            text-align: center;
            border: 1px solid #e0e0e0;
            transition: transform 0.3s ease, box-shadow 0.3s ease;
        }

        .stat-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 8px 25px rgba(0,0,0,0.15);
        }

        .stat-icon {
            font-size: 3em;
            margin-bottom: 15px;
        }

        .stat-number {
            font-size: 2.5em;
            font-weight: bold;
            color: #17a2b8;
            margin-bottom: 10px;
        }

        .stat-label {
            color: #666;
            font-size: 1.1em;
        }

        .records-section {
            background: white;
            border-radius: 15px;
            padding: 30px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        }

        .section-title {
            font-size: 1.5em;
            color: #333;
            margin-bottom: 25px;
            padding-bottom: 15px;
            border-bottom: 2px solid #f0f0f0;
        }

        .record-item {
            display: flex;
            align-items: center;
            padding: 20px;
            border: 1px solid #e0e0e0;
            border-radius: 15px;
            margin-bottom: 15px;
            transition: all 0.3s ease;
            background: white;
            box-shadow: 0 2px 8px rgba(0,0,0,0.08);
        }

        .record-item:hover {
            background: #f8f9fa;
            transform: translateY(-3px);
            box-shadow: 0 8px 25px rgba(0,0,0,0.12);
            border-color: #17a2b8;
        }

        .record-info {
            flex: 1;
        }

        .record-title {
            font-size: 1.2em;
            font-weight: 600;
            color: #333;
            margin-bottom: 5px;
        }

        .record-meta {
            color: #666;
            font-size: 0.9em;
            display: flex;
            gap: 20px;
        }

        .record-score {
            text-align: center;
            margin-right: 20px;
        }

        .score-display {
            font-size: 1.8em;
            font-weight: bold;
            margin-bottom: 5px;
        }

        .score-total {
            color: #666;
            font-size: 0.9em;
        }

        .score-excellent {
            color: #28a745;
        }

        .score-good {
            color: #17a2b8;
        }

        .score-average {
            color: #ffc107;
        }

        .score-poor {
            color: #dc3545;
        }

        .record-actions {
            display: flex;
            gap: 10px;
        }

        .btn-detail {
            background: #667eea;
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 6px;
            cursor: pointer;
            font-size: 0.9em;
            transition: all 0.3s ease;
        }

        .btn-detail:hover {
            background: #5a6fd8;
            transform: translateY(-1px);
        }

        .empty-state {
            text-align: center;
            padding: 60px 20px;
            color: #666;
        }

        .empty-icon {
            font-size: 4em;
            margin-bottom: 20px;
            opacity: 0.5;
        }

        .empty-title {
            font-size: 1.5em;
            margin-bottom: 10px;
            color: #333;
        }

        .empty-description {
            font-size: 1em;
            line-height: 1.5;
        }

        .loading {
            text-align: center;
            padding: 40px;
            color: #666;
        }

        .loading-spinner {
            display: inline-block;
            width: 40px;
            height: 40px;
            border: 4px solid #f3f3f3;
            border-top: 4px solid #17a2b8;
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin-bottom: 20px;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        .grade-badge {
            display: inline-block;
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 0.8em;
            font-weight: 600;
            text-transform: uppercase;
        }

        .grade-excellent {
            background: linear-gradient(135deg, #28a745, #20c997);
            color: white;
        }

        .grade-good {
            background: linear-gradient(135deg, #17a2b8, #138496);
            color: white;
        }

        .grade-average {
            background: linear-gradient(135deg, #ffc107, #e0a800);
            color: white;
        }

        .grade-poor {
            background: linear-gradient(135deg, #dc3545, #c82333);
            color: white;
        }
    </style>
</head>
<body>
    <!-- 顶部导航栏 -->
    <nav class="navbar">
        <div class="container-fluid">
            <div style="display: flex; justify-content: space-between; align-items: center; width: 100%;">
                <a href="index.html" class="navbar-brand">
                    📚 局域网视频学习系统
                </a>
                <div style="display: flex; align-items: center; gap: 20px;">
                    <a href="index.html" style="color: var(--neutral-dark); text-decoration: none;">
                        🏠 首页
                    </a>
                    <a href="favorites.html" style="color: var(--neutral-dark); text-decoration: none;">
                        ❤️ 我的收藏
                    </a>
                    <a href="playlists.html" style="color: var(--neutral-dark); text-decoration: none;">
                        📋 播放列表
                    </a>
                    <a href="exams.html" style="color: var(--neutral-dark); text-decoration: none;">
                        📝 考试中心
                    </a>
                    <a href="profile.html" style="color: var(--neutral-dark); text-decoration: none;">
                        👤 个人资料
                    </a>
                    <span style="color: var(--neutral-dark);">
                        <span data-user-name>学生</span>
                    </span>
                    <button onclick="logout()" class="logout-btn">
                        退出登录
                    </button>
                </div>
            </div>
        </div>
    </nav>

    <div class="container">
        <div class="page-header">
            <h1 class="page-title">📊 考试记录</h1>
            <p class="page-subtitle">查看您的考试历史和成绩统计</p>
        </div>

        <!-- 统计信息 -->
        <div class="stats-grid" id="statsGrid" style="display: none;">
            <div class="stat-card">
                <div class="stat-icon">📝</div>
                <div class="stat-number" id="totalExams">0</div>
                <div class="stat-label">总考试次数</div>
            </div>
            <div class="stat-card">
                <div class="stat-icon">🎯</div>
                <div class="stat-number" id="avgScore">0</div>
                <div class="stat-label">平均分数</div>
            </div>
            <div class="stat-card">
                <div class="stat-icon">🏆</div>
                <div class="stat-number" id="bestScore">0</div>
                <div class="stat-label">最高分数</div>
            </div>
            <div class="stat-card">
                <div class="stat-icon">📈</div>
                <div class="stat-number" id="passRate">0%</div>
                <div class="stat-label">及格率</div>
            </div>
        </div>

        <!-- 考试记录列表 -->
        <div class="records-section">
            <h2 class="section-title">📋 考试记录</h2>
            
            <div id="loadingState" class="loading">
                <div class="loading-spinner"></div>
                <p>正在加载考试记录...</p>
            </div>

            <div id="recordsList" style="display: none;">
                <!-- 考试记录将在这里动态生成 -->
            </div>

            <div id="emptyState" class="empty-state" style="display: none;">
                <div class="empty-icon">📊</div>
                <h3 class="empty-title">暂无考试记录</h3>
                <p class="empty-description">您还没有参加过任何考试，快去参加考试吧！</p>
                <button class="btn-detail" onclick="goToExamList()" style="margin-top: 20px; padding: 12px 24px; font-size: 1em;">去考试</button>
            </div>
        </div>
    </div>

    <script src="../js/common.js"></script>
    <script>
        let examRecords = [];

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            checkAuth();
            loadExamRecords();
        });

        // 检查用户认证状态
        function checkAuth() {
            const user = UserManager.getCurrentUser();
            if (!user || user.role !== 2) {
                Message.error('请先登录学生账号');
                setTimeout(() => {
                    window.location.href = '../login.html';
                }, 1500);
                return;
            }
            // 更新用户信息显示
            const userNameElement = document.querySelector('[data-user-name]');
            if (userNameElement) {
                userNameElement.textContent = user.name;
            }
        }

        // 加载考试记录
        async function loadExamRecords() {
            try {
                const response = await API.get('/exam/my-records');
                if (response.success) {
                    examRecords = response.records || [];
                    renderStats();
                    renderRecords();
                } else {
                    Message.error(response.message || '加载考试记录失败');
                    showEmptyState();
                }
            } catch (error) {
                console.error('加载考试记录失败:', error);
                Message.error('加载考试记录失败，请稍后重试');
                showEmptyState();
            }
        }

        // 渲染统计信息
        function renderStats() {
            if (examRecords.length === 0) {
                document.getElementById('statsGrid').style.display = 'none';
                return;
            }

            const totalExams = examRecords.length;
            const totalScore = examRecords.reduce((sum, record) => sum + (record.score || 0), 0);
            const avgScore = totalExams > 0 ? Math.round(totalScore / totalExams) : 0;
            const bestScore = Math.max(...examRecords.map(record => record.score || 0));
            const passCount = examRecords.filter(record => (record.score || 0) >= 60).length;
            const passRate = totalExams > 0 ? Math.round((passCount / totalExams) * 100) : 0;

            document.getElementById('totalExams').textContent = totalExams;
            document.getElementById('avgScore').textContent = avgScore;
            document.getElementById('bestScore').textContent = bestScore;
            document.getElementById('passRate').textContent = passRate + '%';

            document.getElementById('statsGrid').style.display = 'grid';
        }

        // 渲染考试记录列表
        function renderRecords() {
            const recordsList = document.getElementById('recordsList');
            const loadingState = document.getElementById('loadingState');
            const emptyState = document.getElementById('emptyState');

            loadingState.style.display = 'none';

            if (examRecords.length === 0) {
                showEmptyState();
                return;
            }

            recordsList.innerHTML = examRecords.map(record => {
                const percentage = record.totalQuestions > 0 ? 
                    Math.round((record.score / record.totalQuestions) * 100) : 0;
                const gradeClass = getGradeClass(percentage);
                const gradeText = getGradeText(percentage);

                return `
                    <div class="record-item">
                        <div class="record-info">
                            <div class="record-title">${record.examTitle || '未知考试'}</div>
                            <div class="record-meta">
                                <span>📅 ${formatDate(record.examTime)}</span>
                                <span>📊 总分: ${record.totalQuestions} 分</span>
                                <span class="grade-badge ${gradeClass}">${gradeText}</span>
                            </div>
                        </div>
                        <div class="record-score">
                            <div class="score-display ${gradeClass}">${record.score}</div>
                            <div class="score-total">/ ${record.totalQuestions}</div>
                        </div>
                        <div class="record-actions">
                            <button class="btn-detail" onclick="viewExamDetail(${record.id})">
                                查看详情
                            </button>
                        </div>
                    </div>
                `;
            }).join('');

            recordsList.style.display = 'block';
        }

        // 显示空状态
        function showEmptyState() {
            document.getElementById('loadingState').style.display = 'none';
            document.getElementById('recordsList').style.display = 'none';
            document.getElementById('emptyState').style.display = 'block';
        }

        // 获取成绩等级样式
        function getGradeClass(percentage) {
            if (percentage >= 90) return 'score-excellent';
            if (percentage >= 80) return 'score-good';
            if (percentage >= 60) return 'score-average';
            return 'score-poor';
        }

        // 获取成绩等级文本
        function getGradeText(percentage) {
            if (percentage >= 90) return '优秀';
            if (percentage >= 80) return '良好';
            if (percentage >= 60) return '及格';
            return '不及格';
        }

        // 查看考试详情
        async function viewExamDetail(recordId) {
            try {
                // 根据recordId找到对应的examId
                const record = examRecords.find(r => r.id === recordId);
                if (!record) {
                    Message.error('考试记录不存在');
                    return;
                }

                const examId = record.examId;
                if (!examId) {
                    Message.error('无法获取考试ID');
                    return;
                }
                
                const response = await API.get(`/exam/answer-detail/${examId}`);
                if (response.success) {
                    // 保存详情数据并跳转到详情页面
                    sessionStorage.setItem('examDetail', JSON.stringify({
                        exam: response.exam,
                        record: record,
                        answers: response.answers,
                        examRecord: response.record
                    }));
                    window.location.href = `exam-result.html?examId=${examId}`;
                } else {
                    Message.error(response.message || '获取考试详情失败');
                }
            } catch (error) {
                console.error('获取考试详情失败:', error);
                Message.error('获取考试详情失败，请稍后重试');
            }
        }

        // 跳转到考试列表
        function goToExamList() {
            window.location.href = 'exams.html';
        }

        // 格式化日期
        function formatDate(dateString) {
            if (!dateString) return '未知';
            const date = new Date(dateString);
            return date.toLocaleDateString('zh-CN', {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit'
            });
        }

        // 退出登录
        async function logout() {
            if (confirm('确定要退出登录吗？')) {
                try {
                    UserManager.logout();
                    window.location.href = '../login.html';
                } catch (error) {
                    console.error('退出登录失败:', error);
                    Message.error('退出登录失败');
                }
            }
        }
    </script>
</body>
</html>
